var express = require('express');
var path = require('path');
var mongoose = require('mongoose');

var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var serveStatic = require('serve-static');
var mongoStore = require('connect-mongo')(session);
var logger = require('morgan');
var port = process.env.PORT || 3001;
var app = express();
var fs = require('fs');
var mocha = require('mocha');

var env = process.env.NODE_ENV || 'development';
var dbUrl = 'mongodb://node_site_runner:lemons@127.0.0.1:27017/node-site';

if (env === 'development') {
	dbUrl = 'mongodb://localhost:27017/node-site';
}


mongoose.Promise = global.Promise;
mongoose.connect(dbUrl);
mongoose.connection.on('connected', function(){
    console.log('Connection success!');
});
mongoose.connection.on('error', function(err){
    console.log('Connection error: ' + err);
});
mongoose.connection.on('disconnected', function(){
    console.log('Connection disconnected');
});

// models loading
var models_path = __dirname + '/app/models';
var walk = function(path) {
	fs
		.readdirSync(path)
		.forEach(function(file) {
			var newPath = path + '/' + file;
			var stat = fs.statSync(newPath);

			if (stat.isFile()) {

				if(/(.*)\.(js|coffee)/.test(file)) {
					require(newPath);
				}
			}
			else if (stat.isDirectory) {
				walk(newPath);
			}
		})
}
walk(models_path);

app.set('views', './app/views/pages');
app.set('view engine', 'jade');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
	secret: 'node-site',
	store: new mongoStore({
		url: dbUrl,
		collection: 'sessions'
	})
	//resave: false,
	//saveUninitialized: true
}));

var env = process.env.NODE_ENV || 'development';
if('development' === env) {
	app.set('showStackError', true);
	app.use(logger(':method :url :status'));
	app.locals.pretty = true;
	mongoose.set('debug', true);
}

require('./config/routes')(app);

app.listen(port);
app.locals.moment = require('moment');
app.use(serveStatic(path.join(__dirname, 'public')));

console.log('site started on port ' + port);

